package com.sll.hosptials.service.impl;

import com.sll.hosptials.model.UserInfo;
import com.sll.hosptials.service.ExcelService;
import com.sll.hosptials.service.UserInfoService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.concurrent.*;

@Service
public class ExcelServiceImpl implements ExcelService {

    @Resource
    private UserInfoService userInfoService;

    @Override
    public  Boolean importExcel(LinkedList<UserInfo> data) {
        // 获取服务器的 CPU 核心数
        int coreCount = Runtime.getRuntime().availableProcessors();
        // 根据核心数设置合适的线程池参数
        int corePoolSize = Math.min(coreCount * 2, 6); // 核心线程数为 CPU 核心数的两倍，最大不超过 6
        int maximumPoolSize = corePoolSize * 2; // 最大线程数为核心线程数的两倍
        long keepAliveTime = 60; // 线程空闲超时时间为 60 秒

        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), new ThreadFactory() {
                    @Override
                    public Thread newThread(@NotNull Runnable r) {
                        return new Thread(r);
                    }
                });
        threadPoolExecutor.execute(() -> {
            try {
                userInfoService.saveBatch(data);
                System.out.println("Executing logic code in a thread");
            } catch (Exception e) {
                // 处理异常情况
                e.printStackTrace();
            }
        });
//        任务执行完毕关闭线程池
        threadPoolExecutor.shutdown();
        return true;
    }

//    public static void main(String[] args) {
//        int su = 1000;
//        int count = 0;
////        范围
//        for (int i = 2; i < su; i++) {
////            整除的数据
//            for (int i1 = 2; i1 < i; i1++) {
//                if (i % i1 == 0) {
//                    count++;
//                }
//            }
//            if (count == 0) {
//                System.out.println("i=" + i);
//            }
//            count = 0;
//        }
//    }


}
